package com.hfut.eeg.service;

import com.hfut.eeg.common.util.GenerateCommon;
import com.hfut.eeg.common.util.JwtTokenUtil;
import com.hfut.eeg.dao.LoginMapper;
import com.hfut.eeg.dto.LoginParam;
import com.hfut.eeg.dto.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @author 梁琦
 * @program: eeg
 * @Package com.hfut.eeg.service
 * @Description: TODO
 * @date 2019-11-05 11:11
 */
@Service
@Scope("singleton")
public class LoginService {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginService.class);

    @Autowired
    private LoginMapper login;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AdminUserdetailService userdetailService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private GenerateCommon common;

    @Autowired

    private SetupService setupService;

    @Autowired
    private LoginService service;

    /**
    * 判断是否有用户，如果有，就存入Context中
    */
    public HashMap<String,Object> userLogin(LoginParam param){
        String token = null;
        HashMap<String,Object> result = new HashMap<>();
        try {
            //通过用户名查询用户信息
            UserDetails userDetails = userdetailService.loadUserByUsername(param.getUserName());
            if(!passwordEncoder.matches(param.getUserPassword(),userDetails.getPassword())){
                throw new BadCredentialsException("密码不正确");
            }
            //通过验证，进行存储
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
            //比较的好的方式还是应该实现UserDetails
            result.put("user",service.getUserByUserName(param.getUserName()));
        }catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
            return null;
        }
        result.put("token",token);
        //System.out.println(result);

        return result;
    }

    /**
    * 根据用户名获取用户
    */
    public User getUserByUserName(String userName){
        return login.getUserByUserName(userName);
    }

    /**
    * 用户注册
    */
    public int userRegister(User user){
        user.setUserPassword(passwordEncoder.encode(user.getUserPassword()));
        common.initID(setupService);
        user.setUserId(common.generateID(setupService));
        //System.out.println("userRegister:"+user);
        return login.registerUser(user);
    }

}
